<template>
  <div class="main-container">
    <div class="header">
      <div style="display: flex; align-items: center;">
        <el-icon size="24" style="margin-right: 10px;"><Monitor /></el-icon>
        <h2>设备管理系统</h2>
      </div>
      <div style="display: flex; align-items: center;">
        <span style="margin-right: 15px;">欢迎，{{ username }}</span>
        <el-button type="text" @click="handleLogout" style="color: white;">
          <el-icon><SwitchButton /></el-icon>
          退出登录
        </el-button>
      </div>
    </div>
    
    <div class="content">
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
        <h3>二级设备列表 - 主设备IMEI: {{ mainImei }}</h3>
        <div>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            添加二级设备
          </el-button>
          <el-button @click="$router.push('/devices')">
            <el-icon><ArrowLeft /></el-icon>
            返回主设备列表
          </el-button>
        </div>
      </div>
      
      <!-- 原始表格 -->
      <el-table :data="subDevices" border stripe v-loading="loading">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="subDeviceId" label="二级设备ID" width="120" />
        <el-table-column prop="deviceName" label="设备名称" width="150" show-overflow-tooltip />
        <el-table-column prop="deviceModel" label="设备型号" width="120" />
        <el-table-column prop="responseTimeout" label="轮询应答超时时间(ms)" width="180" />
        <el-table-column prop="pollingInterval" label="轮询周期时间(ms)" width="180" />
        <el-table-column prop="createdTime" label="创建时间">
          <template #default="scope">
            {{ formatTime(scope.row.createdTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleViewKeys(scope.row)">
              <el-icon><Document /></el-icon>
              Modbus配置
            </el-button>
            <el-button type="warning" size="small" @click="handleEdit(scope.row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 备选表格 (手动构建) -->
      <div style="margin-top: 20px; overflow-x: auto;">
        <table style="width: 100%; border-collapse: collapse; border: 1px solid #ebeef5;">
          <thead>
            <tr style="background-color: #f5f7fa;">
              <th style="padding: 12px; border: 1px solid #ebeef5;">二级设备ID</th>
              <th style="padding: 12px; border: 1px solid #ebeef5;">设备名称</th>
              <th style="padding: 12px; border: 1px solid #ebeef5;">设备型号</th>
              <th style="padding: 12px; border: 1px solid #ebeef5;">轮询应答超时时间(ms)</th>
              <th style="padding: 12px; border: 1px solid #ebeef5;">轮询周期时间(ms)</th>
              <th style="padding: 12px; border: 1px solid #ebeef5;">创建时间</th>
              <th style="padding: 12px; border: 1px solid #ebeef5;">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="device in subDevices" :key="device.id" style="border-bottom: 1px solid #ebeef5;">
              <td style="padding: 12px; border: 1px solid #ebeef5;">{{ device.subDeviceId }}</td>
              <td style="padding: 12px; border: 1px solid #ebeef5;">{{ device.deviceName }}</td>
              <td style="padding: 12px; border: 1px solid #ebeef5;">{{ device.deviceModel }}</td>
              <td style="padding: 12px; border: 1px solid #ebeef5;">{{ device.responseTimeout }}</td>
              <td style="padding: 12px; border: 1px solid #ebeef5;">{{ device.pollingInterval }}</td>
              <td style="padding: 12px; border: 1px solid #ebeef5;">{{ formatTime(device.createdTime) }}</td>
              <td style="padding: 12px; border: 1px solid #ebeef5;">
                <el-button type="primary" size="small" @click="handleViewKeys(device)">Modbus配置</el-button>
                <el-button type="warning" size="small" @click="handleEdit(device)">编辑</el-button>
                <el-button type="danger" size="small" @click="handleDelete(device)">删除</el-button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <!-- 调试信息 -->
      <div v-if="subDevices.length > 0" style="margin-top: 20px; padding: 10px; background-color: #f0f9eb; border-radius: 4px;">
        <h4>调试信息</h4>
        <p>设备数量: {{ subDevices.length }}</p>
        <div v-for="(device, index) in subDevices" :key="index" style="margin-bottom: 10px; padding: 10px; border: 1px solid #ddd;">
          <p><strong>ID:</strong> {{ device.id }}</p>
          <p><strong>二级设备ID:</strong> {{ device.subDeviceId }}</p>
          <p><strong>设备名称:</strong> {{ device.deviceName }}</p>
          <p><strong>设备型号:</strong> {{ device.deviceModel }}</p>
        </div>
      </div>
      
      <div style="display: flex; justify-content: space-between; margin-top: 20px;">
        <el-button type="danger" @click="handleBatchDelete" :disabled="selectedRows.length === 0">
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :small="false"
          :disabled="false"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

export default {
  name: 'SubDeviceList',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const loading = ref(false)
    const username = ref(sessionStorage.getItem('username') || '')
    const mainImei = ref(route.params.mainImei)
    const subDevices = ref([])
    const selectedRows = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)

    const loadSubDevices = async () => {
      try {
        loading.value = true
        const token = sessionStorage.getItem('token')
        const response = await axios.get(`/api/sub-devices/main/${mainImei.value}`, {
          headers: { Authorization: `Bearer ${token}` }
        })
        
        if (response.data.success) {
          subDevices.value = response.data.data
          total.value = response.data.data.length
          
          // 调试输出
          console.log('加载的设备数据:', subDevices.value)
          if (subDevices.value.length > 0) {
            console.log('第一个设备:', subDevices.value[0])
            console.log('设备名称:', subDevices.value[0].deviceName)
          }
        } else {
          ElMessage.error(response.data.message)
        }
      } catch (error) {
        ElMessage.error('加载二级设备列表失败')
      } finally {
        loading.value = false
      }
    }

    const handleAdd = () => {
      router.push(`/sub-devices/${mainImei.value}/add`)
    }

    const handleEdit = (subDevice) => {
      router.push(`/sub-devices/edit/${subDevice.id}`)
    }

    const handleViewKeys = (subDevice) => {
      router.push(`/device-keys/${subDevice.id}`)
    }

    const handleDelete = async (subDevice) => {
      try {
        await ElMessageBox.confirm('确定要删除这个二级设备吗？', '警告', {
          type: 'warning'
        })
        
        const token = sessionStorage.getItem('token')
        const response = await axios.delete(`/api/sub-devices/${subDevice.id}`, {
          headers: { Authorization: `Bearer ${token}` }
        })
        
        if (response.data.success) {
          ElMessage.success('删除成功')
          loadSubDevices()
        } else {
          ElMessage.error(response.data.message)
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }

    const handleBatchDelete = async () => {
      if (selectedRows.value.length === 0) {
        ElMessage.warning('请选择要删除的分设备')
        return
      }
      
      try {
        await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 个分设备吗？`, '警告', {
          type: 'warning'
        })
        
        const token = sessionStorage.getItem('token')
        const ids = selectedRows.value.map(row => row.id)
        const response = await axios.delete('/api/sub-devices/batch', {
          data: ids,
          headers: { Authorization: `Bearer ${token}` }
        })
        
        if (response.data.success) {
          ElMessage.success('批量删除成功')
          loadSubDevices()
        } else {
          ElMessage.error(response.data.message)
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('批量删除失败')
        }
      }
    }

    const handleSizeChange = (newSize) => {
      pageSize.value = newSize
      currentPage.value = 1
      loadSubDevices()
    }

    const handleCurrentChange = (newPage) => {
      currentPage.value = newPage
      loadSubDevices()
    }

    const formatTime = (timestamp) => {
      if (!timestamp) return ''
      return new Date(timestamp).toLocaleString()
    }

    const handleLogout = () => {
      sessionStorage.removeItem('token')
      sessionStorage.removeItem('username')
      router.push('/login')
    }

    onMounted(() => {
      console.log('组件已挂载，开始加载数据...')
      // 强制延迟一点时间再加载数据，确保DOM已完全渲染
      setTimeout(() => {
        loadSubDevices()
      }, 100)
    })

    return {
      loading,
      username,
      mainImei,
      subDevices,
      selectedRows,
      currentPage,
      pageSize,
      total,
      handleAdd,
      handleEdit,
      handleViewKeys,
      handleDelete,
      handleBatchDelete,
      handleSizeChange,
      handleCurrentChange,
      formatTime,
      handleLogout
    }
  }
}
</script>

<style scoped>
.main-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 15px 30px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.content {
  padding: 30px;
  max-width: 1200px;
  margin: 0 auto;
}

.el-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

/* 调试样式 */
.el-table th {
  background-color: #f0f9eb !important;
}

.el-table td {
  padding: 8px 0;
}

/* 确保设备名称列可见 */
.el-table .cell {
  white-space: nowrap;
  overflow: visible;
}
</style>